package com.hivis.websocket;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;

import java.io.IOException;
import java.util.Date;

/**
 * 向客户端推送数据的任务类
 */
@Component
public class MessageSendTask {

    @Autowired(required = true)
    @Qualifier("mywebsockethandler")
    MyWebSocketHandler myWebSocketHandler;

    private final static Logger sysLogger = LoggerFactory.getLogger("system");
    //	private final static Logger loginLogger = LoggerFactory.getLogger("login");
    private final static Logger bizMessageLogger = LoggerFactory.getLogger("bizMessage");

    private final String SOFT_TRIGGER_TEXT = "[软讯]";

    // fastjson对Date的处
    private static SerializeConfig mapping = new SerializeConfig();
    private static String dateFormat;

    static {
        dateFormat = "yyyy-MM-dd HH:mm:ss";
        mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat));
    }

    public void handleWarning(JSONObject dataJSON) {
    }

    public void notifyBrower() {
        // 通知客户端
        JSONObject json = new JSONObject();

        String textMessage = JSONObject.toJSONString(json, mapping);
        // System.out.println("通知客户端："+ textMessage);
        // 通知浏览器端新数据
        try {
            myWebSocketHandler.sendMessageToBrower(new TextMessage(""), null);
        } catch (IOException e) {
            e.printStackTrace();
            sysLogger.error("sendMessageToBrower: {} exception:{}", textMessage, e);
        }
    }
}
